package com.atlassian.jira.server;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.atlassian.jira.plugin.JarDependenciesLoader;

/**
 * The purpose of having this class is to:
 * 
 * 1. Prevent JIRA to complain about class loading issues (as we use class
 * loading isolation on inner JARs).
 * 
 * 2. Decouple JIRA knowledge from the REST server.
 * 
 * @author yclian
 * 
 */
public class JiraRestServerWrapper implements JiraRestServer {

	private static final Logger LOGGER = Logger.getLogger(JiraRestServerWrapper.class);

	private JiraRestServer jiraRestServer = null;
	
	public JiraRestServerWrapper() throws Exception {
		this(newJiraRestServerInstance());
	}

	private static JiraRestServer newJiraRestServerInstance() 
		throws Exception{
		
		JiraRestServer jiraRestServer = null;
		
		try {
			jiraRestServer = (JiraRestServer) (new JarDependenciesLoader()).loadClass("com.atlassian.jira.server.DefaultJiraRestServer").newInstance();
		} catch (Exception e) {
			LOGGER.error("Could not load inner JAR dependencies", e);
			throw e;
		}
		
		return jiraRestServer;
	}

	public JiraRestServerWrapper(JiraRestServer jiraRestServer) throws Exception {

		this.jiraRestServer = jiraRestServer;

		Map<Properties, String> properties = new HashMap<Properties, String>();
		properties.put(JiraRestServer.Properties.ADDRESS, "http://localhost:8082/");
		properties.put(JiraRestServer.Properties.IN_INTERCEPTORS,
				"org.apache.cxf.interceptor.LoggingInInterceptor, org.apache.cxf.interceptor.StaxInInterceptor");
		properties.put(JiraRestServer.Properties.OUT_INTERCEPTORS,
				"org.apache.cxf.interceptor.LoggingOutInterceptor, org.apache.cxf.interceptor.StaxOutInterceptor");

		this.start(properties);
	}

	public void start(Map<Properties, String> properties) {
		this.jiraRestServer.start(properties);
	}

	public void stop() {
		this.jiraRestServer.stop();
	}

	public JiraRestServer getJiraRestServer() {
		return this.jiraRestServer;
	}

	public void setJiraRestServer(JiraRestServer jiraRestServer) {
		this.jiraRestServer = jiraRestServer;
	}
	
	public static void main(String[] args) throws Exception{
		new JiraRestServerWrapper();
	}
}
